#!/bin/sh
#Auto Batch Add KVM Virtual
#Author wugk 2013-12-17
#Define Variables
XML_DIR=/etc/libvirt/qemu/
KVM_DIR=/data/kvm/
COUNT1=`ls  $XML_DIR|grep xml|tail -1 |sed 's/[^0-9]//g'`
COUNT2=`expr $COUNT1 + 1`
add_kvm()
{
cat <<eof
    #VIR_NAME  RAM{M}     SIZE{g}
    centos01   1024         2
    centos02   512          3
    centos03   1024         4
    centos04   1024         5
    centos05   1024         6
eof
echo "=================================="
if
    [ ! -e kvm.txt ];then
    echo "The kvm.txt File does not exist,Please create ......"
    exit
fi
#Auto Create machines
if
    [ ! -s kvm.txt ];then
    echo "The kvm.txt is empty file ,Please Refer Above Content ......"
    exit
fi
while read line
do
    NAME=`echo $line |grep -v "^#" |awk '{print $1}'`
    RAM=`echo  $line |grep -v "^#" |awk '{print $2}'`
    SIZE=`echo $line |grep -v "^#" |awk '{print $3}'`
    /usr/bin/virt-install --name=${NAME} --ram ${RAM} --vcpus=1 --disk path=/data/kvm/${NAME}.img,size=${SIZE},bus=virtio --accelerate --cdrom /data/iso/centos58.iso --vnc --vncport=-1 --vnclisten=0.0.0.0 --network bridge=br0,model=virtio --noautoconsole
done <kvm.txt
}
clone_kvm()
{
    read -p "Please Enter you want create virtual machines count: " COUNT3
    COUNT4=`expr ${COUNT1} + ${COUNT3}`
    for i in `seq ${COUNT2} ${COUNT4}`
    do
    UUID=`/usr/bin/uuidgen`
    MAC=52\\:54\\:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1\\:\2\\:\3\\:\4/')
    cd $XML_DIR ;cp centos01.xml centos${i}.xml
    cd $XML_DIR ;sed -i -e "/uuid/s:.*:<uuid>$UUID</uuid>:g" -e "s/centos01/centos${i}/g" -e "/<mac/s:.*:<mac address='$MAC'/>:g" centos${i}.xml
    cd $KVM_DIR ;nohup cp centos01.img centos${i}.img &
    /usr/bin/virsh define $XML_DIR/centos${i}.xml
    echo "The Virtual machines Info:"
    echo "The centos${i} Virtual machines created successfull"
    done
}
delete_kvm()
{
    read -p "Please Enter you want deleted virtual machines :" name
    for i in `echo ${name} |sed 's/ /\n/g'`
    do
    /usr/bin/virsh destroy $i
    /usr/bin/virsh undefine $i ;echo "The $i Virtual machines Deleted Successfully"
    done
}
case $1 in
    add_kvm )
    add_kvm
    ;;
    clone_kvm )
    clone_kvm
    ;;
    delete_kvm    )
    delete_kvm
    ;;
    *       )
    echo Usage: $0 "{add_kvm|clone_kvm|delete_kvm|help}"
    ;;
esac